package com.mokio.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @program: xiaomishop
 * @ClassName ImageController
 * @description:验证码生成器
 * @author: mokio
 * @create: 2024−12-11 08:25
 * @Version 1.0
 **/
@Controller
public class ImageController {
    /**
     * 获取验证码的颜色
     * @param min
     * @param max
     * @return
     */

    public static Color getRandomColor(int min ,int max) {
        Random rand = new Random();
        if(min > 255) {
            min = 255;
        }
        if(max > 255) {
            max = 255;
        }

        int r = rand.nextInt(max - min) + min;
        int g = rand.nextInt(max - min) + min;
        int b = rand.nextInt(max - min) + min;


        return new Color(r, g, b);
    }

    @RequestMapping("/yzmcontroller.action")
    @ResponseBody
    public static void yzm(HttpSession session, HttpServletResponse response){
        //规定画图的地方
        int width = 60,height = 20;
        //BufferedImage类描述了一个Image于访问图像缓冲区
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //得到画布
        Graphics g = image.getGraphics();
        //给画布设置颜色
        g.setColor(getRandomColor(200,255));
        //画一个矩形
        g.fillRect(0, 0, width, height);
        //设置字体
        g.setFont(new Font("宋体", Font.PLAIN, 20));

        //画干扰线
        Random r = new Random();
        for (int i = 0; i < 100; i++) {
            int x1=r.nextInt(width);
            int y1=r.nextInt(height);

            int x2=r.nextInt(15);
            int y2=r.nextInt(15);
            //设置干扰线颜色
            g.setColor(getRandomColor(160,199));
            g.drawLine(x1,y1,x2,y2);
        }

        //画干扰点
        for (int i = 0; i < 100; i++) {
            int x1=r.nextInt(width);
            int y1=r.nextInt(height);


            //设置干扰线颜色
            g.setColor(getRandomColor(130,159));
            g.drawOval(x1,y1,0,0);
        }

        //生成数字
        String RS =r.nextInt(9000)+1000+"";
        g.setColor(getRandomColor(80,129));
        //画验证码
        g.drawString(RS,10,16);
        //销毁画布
        g.dispose();
        //存验证码
        session.setAttribute("random",RS);

        try {
            //将图片写到页面上
            ImageIO.write(image,"JPEG",response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
